package com.dkd.handler;

import cn.elegent.ac.ACHandler;
import cn.elegent.ac.annotation.Topic;
import cn.elegent.util.json.JsonUtil;
import com.dkd.config.TopicConfig;
import com.dkd.config.constant.TaskType;
import com.dkd.contract.VmStatusContract;
import com.dkd.feign.VMService;
import com.dkd.http.vo.TaskViewModel;
import com.dkd.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * vmstatus处理程序
 *
 * @author DiXiaoNie
 * @date 2023/02/02
 * @since 2023/2/2 16:12
 */
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VMStatusHandler implements ACHandler<VmStatusContract> {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String topic, VmStatusContract vmStatusContract) throws Exception {
        if (vmStatusContract == null || vmStatusContract.getStatusInfo() == null || vmStatusContract.getStatusInfo().size() <= 0) {
            return;
        }
        try {
            //根据售货机编号查询售货机
            var vmInfo = this.vmService.getVMInfo(vmStatusContract.getInnerCode());
            if (vmInfo == null) {
                return;
            }
            //查询最少工单量用户
            var userId = this.taskService.getLeastUser(vmInfo.getRegionId(), true);
            if (userId != 0) {
                //创建工单对象
                TaskViewModel task = new TaskViewModel();
                //自动工单
                task.setCreateType(0);
                //售货机编码
                task.setInnerCode(vmInfo.getInnerCode());
                //执行人
                task.setUserId(userId);
                //自动工单
                task.setAssignorId(0);
                //工单类型
                task.setProductType(TaskType.TASK_TYPE_REPAIR);
                //将报文进行存储
                task.setDesc(JsonUtil.serialize(vmStatusContract));
                //创建工单
                this.taskService.createTask(task);
            }
        } catch (Exception e) {
            log.error("创建自动维修工单失败, msg is：{}", vmStatusContract);
            e.printStackTrace();
        }
    }
}
